const path = require('path');
const fs = require('fs');
const logger = require('../libs/log').logger;

const getfilePath = function (req) {
    try {
        let files = req.files;
        let result = [];
        if (files && files.length) {
            for (let index = 0; index < files.length; index++) {
                const file = files[index];
                let filepath = file.path;
                let ext = path.parse(file.originalname).ext;
                let newpath = file.path + ext;
                fs.renameSync(filepath, newpath);
                // 删除文件夹文件
                deleteFile(filepath);
                const ROOT_PATH = process.cwd();
                let rootpath = ROOT_PATH + '/' + newpath;
                result.push({
                    path: rootpath,
                    filename: file.originalname,
                    mimetype: file.mimetype,
                    size: file.size,
                    ext: ext
                });
            }
            return result;
        } else {
            return null;
        }
    } catch (err) {
        logger.info('-----getfilePath-----------获取文件路径异常-------------------err:', files);
        throw err
    }
}

var deleteFile = function (filepath) {
    //导入解析成功后 将文件删除
    fs.unlink(filepath, function (err) {
        if (err) throw err;
    })
}

module.exports = {
    getfilePath,
    deleteFile
}
